<?php

class KeObjectBuilder extends SfObjectBuilder
{

	/**
	 *
	 */

	protected function addRestorePk(&$script) {


		$script .= "
	/**
	 *  Reestablece los valores originales de las llaves primarias
	 */
	public function restorePk()
	{
";
		foreach ($this->getTable()->getColumns() as $col) {
			$clo = strtolower($col->getName());
			if ($col->isPrimaryKey()) {
				$script .= "
		 \$this->$clo = \$this->$clo"."_old;";
			}
		}
		$script .= "
	}
";
	}

  /*  protected function addBuildPkeyCriteria(&$script)
    {
         $tmp = "";
         parent::addBuildPkeyCriteria($tmp);
         
         $tmp2 = str_replace(");", "_old);", $tmp);
         $tmp2 = str_replace("NAME_old);", "NAME);", $tmp2);
         $script .= $tmp2;
         
         $this->addRestorePk($script);
         
    }*/
/*
	protected function addHydrate(&$script)
	{
		$table = $this->getTable();
		$platform = $this->getPlatform();

		$script .= "

	public function hydrate(\$row, \$startcol = 0, \$rehydrate = false)
	{
		try {
";
		$n = 0;
		foreach ($table->getColumns() as $col) 
        {
			if (!$col->isLazyLoad()) 
            {
				$clo = strtolower($col->getName());
				if ($col->isLobType() && !$platform->hasStreamBlobImpl()) 
                {
					$script .= "
			if (\$row[\$startcol + $n] !== null) {
				\$this->$clo = fopen('php://memory', 'r+');
				fwrite(\$this->$clo, \$row[\$startcol + $n]);
				rewind(\$this->$clo);
			} else {
				\$this->$clo = null;
			}";
				} elseif ($col->isPhpPrimitiveType()) 
                {
					$script .= "
			\$this->$clo = (\$row[\$startcol + $n] !== null) ? (".$col->getPhpType().") \$row[\$startcol + $n] : null;";
			        if($col->isPrimaryKey()) 
                    {
                    $script .= " 
             \$this->".$clo."_old = (\$row[\$startcol + $n] !== null) ? (".$col->getPhpType().") \$row[\$startcol + $n] : null;";
                    }
            	} elseif ($col->isPhpObjectType()) 
                {
					$script .= "
			\$this->$clo = (\$row[\$startcol + $n] !== null) ? new ".$col->getPhpType()."(\$row[\$startcol + $n]) : null;";
				} else 
                {
					$script .= "
			\$this->$clo = \$row[\$startcol + $n];";
                    if($col->isPrimaryKey()) 
                    {
                    $script .= " 
             \$this->".$clo."_old = \$row[\$startcol + $n];";   
                    }
				}
				$n++;
			} // if col->isLazyLoad()
		} 

		if ($this->getBuildProperty("addSaveMethod")) {
			$script .= "
			\$this->resetModified();
";
		}

		$script .= "
			\$this->setNew(false);

			if (\$rehydrate) {
				\$this->ensureConsistency();
			}

			// FIXME - using NUM_COLUMNS may be clearer.
			return \$startcol + $n; // $n = ".$this->getPeerClassname()."::NUM_COLUMNS - ".$this->getPeerClassname()."::NUM_LAZY_LOAD_COLUMNS).

		} catch (Exception \$e) {
			throw new PropelException(\"Error populating ".$table->getPhpName()." object\", \$e);
		}
	}
";

	} // addHydrate()
*/

	/**
	 * Crea variables para las pk.
	 * @param      string &$script The script will be modified in this method.
	 * @see        addColumnNameConstants()
	 */
	protected function addColumnAttributesPkOld(&$script) {

		$table = $this->getTable();
		foreach ($table->getColumns() as $col) 
        {
			$cptype = $col->getPhpNative();
			$clo=strtolower($col->getName());
			$script .= "
	/**
	 * The value for the $clo_old field.
	 * @var        $cptype
	 */

";
            // 2008-03-18 geacosta "Variables creadas para permitir modificar llaves foraneas sin crear nuevos registros"
            if ($col->isPrimaryKey()) 
            {
                $script .= "    protected \$" . $clo ."_old ;";		    
            }

		}  // foreach col

	} // addColumnAttributes()
/*	
    protected function addAttributes(&$script)
    { 
        parent::addAttributes($script);
        $this->addColumnAttributesPkOld($script);
    }
*/

  private function addFunctionSave(&$script)
  {
	$table = $this->getTable();
		$reloadOnUpdate = $table->isReloadOnUpdate();
		$reloadOnInsert = $table->isReloadOnInsert();
		
		$script .= "
	/**
	 * Persists this object to the database.
	 * 
	 * If the object is new, it inserts it; otherwise an update is performed.
	 * All modified related objects will also be persisted in the doSave() 
	 * method.  This method wraps all precipitate database operations in a 
	 * single transaction.";
		if ($reloadOnUpdate) {
			$script .= "
	 * 
	 * Since this table was configured to reload rows on update, the object will
	 * be reloaded from the database if an UPDATE operation is performed (unless 
	 * the \$skipReload parameter is TRUE).";
		}
		if ($reloadOnInsert) {
			$script .= "
	 * 
	 * Since this table was configured to reload rows on insert, the object will
	 * be reloaded from the database if an INSERT operation is performed (unless 
	 * the \$skipReload parameter is TRUE).";
		}
		$script .= "
	 *
	 * @param      PropelPDO \$con";
		if ($reloadOnUpdate || $reloadOnInsert) {
			$script .= "
	 * @param      boolean \$skipReload Whether to skip the reload for this object from database.";
		}
		$script .= "	 
	 * @return     int The number of rows affected by this insert/update and any referring fk objects' save() operations.
	 * @throws     PropelException
	 * @see        doSave()
	 */
	public function save(PropelPDO \$con = null".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload = false" : "").")
	{
		if (\$this->isDeleted()) {
			throw new PropelException(\"You cannot save an object that has been deleted.\");
		}

		if (\$con === null) {
			\$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE);
		}

		try {
		    if(\$this->validate())
		    {
    			\$con->beginTransaction();
    			\$affectedRows = \$this->doSave(\$con".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload" : "").");
    			\$con->commit();
    			".$this->getPeerClassname()."::addInstanceToPool(\$this);
    			return true;
			}else
			{
			     //\$this->restorePk();
                 return false;
            }
		} catch (PropelException \$e) {
			\$con->rollback();
			//throw \$e;
			// \$this->restorePk();
			ErrorLog::reportarError('errors', 'error',  \$e->getMessage() );
			return false;
		}
	}
";  
  }

  protected function addSave(&$script)
  {
    $tmp = '';
    $this->addFunctionSave($tmp);

    // add support for created_(at|on) and updated_(at|on) columns
    $date_script = '';
    $updated = false;
    $created = false;
    foreach ($this->getTable()->getColumns() as $col)
    {
      $clo = strtolower($col->getName());

      if (!$updated && in_array($clo, array('updated_at', 'updated_on')))
      {
        $updated = true;
        $date_script .= "
    if (\$this->isModified() && !\$this->isColumnModified(".$this->getColumnConstant($col)."))
    {
      \$this->set".$col->getPhpName()."(time());
    }
";
      }
      else if (!$created && in_array($clo, array('created_at', 'created_on')))
      {
        $created = true;
        $date_script .= "
    if (\$this->isNew() && !\$this->isColumnModified(".$this->getColumnConstant($col)."))
    {
      \$this->set".$col->getPhpName()."(time());
    }
";
      }
    }
    $tmp = preg_replace('/{/', '{'.$date_script, $tmp, 1);

    if (DataModelBuilder::getBuildProperty('builderAddBehaviors'))
    {
      // add sfMixer call
      $pre_mixer_script = "

    foreach (sfMixer::getCallables('{$this->getClassname()}:save:pre') as \$callable)
    {
      \$affectedRows = call_user_func(\$callable, \$this, \$con);
      if (is_int(\$affectedRows))
      {
        return \$affectedRows;
      }
    }

";
      $post_mixer_script = <<<EOF

    foreach (sfMixer::getCallables('{$this->getClassname()}:save:post') as \$callable)
    {
      call_user_func(\$callable, \$this, \$con, \$affectedRows);
    }

EOF;
      $tmp = preg_replace('/{/', '{'.$pre_mixer_script, $tmp, 1);
      $tmp = preg_replace('/(\$con\->commit\(\);)/', '$1'.$post_mixer_script, $tmp);
    }

    // update current script
    $script .= $tmp;
  }

}

?>
